<template>
    <div>
        <el-form :model="form" :rules="rules" label-width="auto" ref="formInstance">
            <el-form-item prop="OrderId" label="项目负责人">
                <UserSelect v-model="form.Leader" v-model:label="form.LeaderName" placeholder="请选择项目负责人" />
            </el-form-item>
            <el-form-item prop="ProjectName" label="项目名称">
                <el-input v-model="form.ProjectName" />
            </el-form-item>
            <el-form-item prop="Period" label="项目周期">
                <el-input v-model="form.Period" />
            </el-form-item>
            <el-form-item>
                <el-button @click="submitForm(formInstance)">成立</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup lang="ts">
    import { reactive, ref } from 'vue';
    import UserSelect from '../../components/UserSelect.vue';
    import { ElMessage, FormInstance, FormRules } from 'element-plus';
    import projectInfoapi from '../../api/projectInfoapi';

    const { id } = defineProps({
        id: {
            type: Number,
            required: true
        }
    });

    const emit = defineEmits(["onSave"])

    const formInstance = ref<FormInstance>()

    interface ProjectForm {
        Period: string
        ProjectName: string
        Leader: number | null
        LeaderName: string
    }

    const form = ref<ProjectForm>({
        Period: "",
        ProjectName: "",
        Leader: null,
        LeaderName: ""
    });

    const rules = reactive<FormRules<ProjectForm>>({
        Period: [
            { required: true, message: '请输入项目周期', trigger: 'blur' }
        ],
        Leader: [
            { required: true, message: '请选择项目负责人', trigger: 'blur' }
        ]
    });

    // 提交
    const submitForm = async (formEl : FormInstance | undefined) => {
		if (!formEl) return
		await formEl.validate((valid, fields) => {
			if (valid) {
				projectInfoapi.add({...form.value,orderId:id}).then(res => {
					if (res.code == 1) {
						ElMessage.success({
							message: '成功'
						});
					} else {
						ElMessage.error({
							message: '失败'
						});
					}
                    emit("onSave");
				});
			} else {
				console.log('error submit!', fields)
			}
		})
	}

</script>

<style scoped></style>